package vsvm.data.filter.ranking.rankingStuff;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;

import vsvm.data.model.AbstractAttribute;

public class SelectSaved implements Serializable {

	private static final long serialVersionUID = 100L;
	private boolean memory = true;
	private SaveSelected saveSelected = null;
	
	public SelectSaved(SaveSelected ss)
	{
		saveSelected = ss;
	}

	public boolean isMemory() {
		return memory;
	}

	public void setMemory(boolean memory) {
		this.memory = memory;
	}

	public int[] selectSaved(JList lstAttributes)
	{
		ArrayList<AbstractAttribute>selectedAttr = saveSelected.getSelectedAttributes();
		
		int attrSize = lstAttributes.getModel().getSize();
		
		int[] sel = new int[attrSize];
		
		for(int i = 0; i < attrSize; i++)
		{
			sel[i] = -1;
		}
		
		ArrayList<String> arr = new ArrayList<String>();
		for(int i = 0; i < attrSize; i++)
		{
			arr.add(((AbstractAttribute)lstAttributes.getModel().getElementAt(i)).getName());	
		}
		
		String[] savedAttr = null;
		
		if(isMemory() && selectedAttr != null)
		{
			int size = selectedAttr.size();
			
			savedAttr = new String[size];
			for(int i = 0; i < size; i++)
			{
				savedAttr[i] = (selectedAttr.get(i)).getName();	
			}
		} 
		else 
		{	
			JFileChooser fc = saveSelected.getFc();
			int returnVal = fc.showOpenDialog(new JFrame());
	        if (returnVal == JFileChooser.APPROVE_OPTION) 
	        {
	            File file = fc.getSelectedFile();
	            saveSelected.setPath(file.getPath());
	            
	            try 
	            {
					BufferedReader input = new BufferedReader(new FileReader(file));
					String list = input.readLine();
					input.close();
					savedAttr = list.split(",");
				} 
	            catch (IOException e1) 
	            {
					e1.printStackTrace();
				}					            
	        }
		}
		
		if(savedAttr == null)
		{
			return sel;
		}
		
		for(int i = 0, nr = 0; i < savedAttr.length && i < attrSize; i++)
		{
			if(arr.contains(savedAttr[i]))
			{
				nr = arr.indexOf(savedAttr[i]);
				sel[nr] = nr;
			}	
		}
		return sel;
	}

}
